package com.he.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.he.config.MinioConfig;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Component
@Slf4j
public class MinioUtils {

    private static MinioClient minioClient;
    private static final String PATH_SEPARATOR = "/";

    /**
     * 连接地址
     */
    private static String endpoint;
    /**
     * 用户名
     */
    private static String accessKey;
    /**
     * 密码
     */
    private static String secretKey;
    /**
     * 桶名称
     */
    private static String bucketName;

    /**
     * 创建bucket
     */
    public static void createBucket(String bucketName) throws Exception {
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            // 配置存储同策略为Public
            minioClient.setBucketPolicy(SetBucketPolicyArgs.
                    builder().
                    bucket(bucketName).
                    config("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"PublicReadGetObject\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + bucketName + "/*\"]}]}").
                    build());
        }
    }


    /**
     * description: 上传文件
     *
     * @param fileInputStream
     * @param fileName
     * @return
     */
    public  String upload(InputStream fileInputStream, String fileName) {
        String url = "";
        String[] split = fileName.split("\\.");
        String extName = FileNameUtil.extName(fileName);
        extName = "." + extName;
        fileName = "file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + UUID.randomUUID().toString().replace("-", "") + "/" + fileName;
        url = endpoint + "/" + bucketName + "/" + fileName;
        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName).stream(fileInputStream, fileInputStream.available(), -1).build());
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    log.error("上传文件失败", e);
                }
            }
        }
        return url;
    }

    //file参数上传文件：
    public String upload(MultipartFile file) {
        String url = "";
        String fileName = file.getOriginalFilename();
        String[] split = fileName.split("\\.");
        String extName = FileNameUtil.extName(fileName);
        extName = "." + extName;
        fileName = "file/" + DateUtil.format(new Date(), "yyyyMMdd") + "/" + UUID.randomUUID().toString().replace("-", "") + "/" + fileName;
        url = endpoint + "/" + bucketName + "/" + fileName;
        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName).stream(file.getInputStream(), file.getSize(), -1).build());
        } catch (Exception e) {
            log.error("上传文件失败", e);
        }
        return url;
    }


    @Autowired
    public void setMinioClient(MinioClient minioClient, MinioConfig minioConfig) {
        MinioUtils.minioClient = minioClient;
        MinioUtils.endpoint = minioConfig.getEndpoint();
        MinioUtils.accessKey = minioConfig.getAccessKey();
        MinioUtils.secretKey = minioConfig.getSecretKey();
        MinioUtils.bucketName = minioConfig.getBucketName();
    }


    public InputStream download(String url) {
        String fileName = url.split(endpoint + PATH_SEPARATOR + bucketName + PATH_SEPARATOR)[1];
        try {
            return minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
